// pages/confirm_detail/confirm_detail.js
var common = require("../../common/common.js").common;

var QQMapWX = require("../../sdk/qqmap-wx-jssdk.min.js");

var qqmapsdk;

const app = getApp();

const {$Toast: $Toast} = require("../../components/base/index");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        choose_nav: 0,
        info: [],
        date: "",
        search_con: "",
        page_sign: "my",
        clerk: [],
        extract: 0,
        //配送方式
        teamerAllOrder: true,
        bgHidden: true,
        allSelect: 1,
        chooseNum: 0
    },
    // 配送方式标签
    extract: function(e) {
        var that = this;
        let extract = e.currentTarget.dataset.extract;
        that.setData({
            extract: extract,
            page: 1,
            order: []
        });
        that.getData(extract);
    },
    //查看团长总单
    viewAllOrder() {
        var that = this;
        var allorder = that.data.AllOrder;
        this.setData({
            teamerAllOrder: false,
            bgHidden: false
        });
        //如果已经请求过接口，就不再请求
                if (!allorder) {
            that.getAllOrder();
        }
    },
    //取消团长总单模态框
    cancelTeamerAllOrder() {
        this.setData({
            teamerAllOrder: true,
            bgHidden: true
        });
    },
    //获取团长信息
    getMyLeaderInfo: function(leader_id_share) {
        common.request({
            endpoint: "leader/myleaderinfo",
            method: "post",
            data: {
                leader_id_share: leader_id_share,
                openid: wx.getStorageSync("user").openid
            },
            success: res => {
                console.log(res.extra, "tuanzhang");
                this.setData({
                    myleaderinfo: res.extra
                });
            }
        });
    },
    //一键收货
    totalButt: common.throttle(function(e) {
        var that = this;
        //var order_ids = that.data.order_ids;
        //var order_ids = "";
                var item_ids = that.data.item_ids;
        let num = 0;
        // that.data.info.orders.forEach((item, index) => {
        //   if (item.select == 1 && !order_ids) {
        //     num++;
        //     order_ids += item.id;
        //   } else if (item.select == 1 && !!order_ids) {
        //     order_ids += ("," + item.id)
        //   }
        // })
        // if (num == 0) {
        //   wx.showToast({
        //     title: '您还没有选择收货订单',
        //     icon: "none"
        //   })
        //   return false;
        // }
                if (!item_ids) {
            wx.showToast({
                title: "您还没有选择收货订单",
                icon: "none"
            });
            return false;
        }
        //判断订单状态，待收货可以点击，已收货提示已收货
                var orderstatus = that.data.orderstatus;
        //if (orderstatus == 1) {
                common.request({
            endpoint: "My/waitpick/leader_receive2",
            method: "post",
            data: {
                item_ids: item_ids,
                //item_ids
                openid: wx.getStorageSync("user").openid
            },
            success: res => {
                console.log(res, "yijian");
                // wx.showToast({
                //   title: res.message
                // })
                                $Toast({
                    content: "一键收货成功" || res.message
                });
                // that.setData({
                //   orderstatus: 0
                // })
                                setTimeout(() => {
                    // wx.navigateBack({
                    // })
                    var chooseNav = that.data.extract;
                    //清空数据
                                        that.setData({
                        info: null
                    });
                    //重新获取订单数据
                                        that.getData(chooseNav);
                }, 1500);
                //that.getData(that.data.extract)
                        },
            fail(res) {
                if (res.code == 2) {
                    $Toast({
                        content: res.message
                    });
                } else {
                    $Toast({
                        content: "取货失败"
                    });
                }
            }
        });
        // } else {
        //   // wx.showToast({
        //   //   title: '所有订单都已收货',
        //   // })
        //   $Toast({
        //     content: "所有订单都已收货"
        //   });
        // }
        }, 2e3),
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        wx.hideShareMenu();
        //创建地图
                wx.createMapContext("my_map", this);
        this.setData({
            date: options.date,
            clerk: wx.getStorageSync("clerk"),
            domain: app.globalData.domain.slice(0, -10)
        });
        //实例化
                common.getAppBase().then(() => {
            qqmapsdk = new QQMapWX({
                key: that.data.appBase.location_key
            });
            this.getData(0);
        });
        this.getBase();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        this.getMyLeaderInfo();
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    choose_nav: function(e) {
        var id = e.currentTarget.dataset.id;
        this.setData({
            choose_nav: id
        });
    },
    getData: function(num) {
        var that = this;
        var clerk = that.data.clerk;
        var openid = "";
        if (clerk.wom_status == 0) {
            openid = wx.getStorageSync("user").openid;
        } else {
            openid = clerk.leader_openid;
        }
        var date = that.data.date;
        var item_ids = "";
        common.request({
            endpoint: "My/waitpick/leader_wait_detail2",
            method: "post",
            data: {
                openid: openid,
                date: date,
                delivery_channel: num
            },
            success: res => {
                //console.log(res,"huoqu")
                var data = res.extra;
                //var order_ids = res.extra.order_ids.split(",");
                                var chooseNum = 0;
                if (data.aa) {
                    data.aa[0].forEach((listItem, listIdx) => {
                        listItem.product_info.forEach((item, index) => {
                            item.select = 1;
                            //默认选中
                            //item.id = order_ids[index]; //增加订单id
                                                        chooseNum++;
                            if (item_ids) {
                                item_ids += "," + item.id;
                            } else {
                                item_ids = item.id;
                            }
                        });
                    });
                }
                if (data.bb) {
                    data.bb[0].forEach((listItem, listIdx) => {
                        listItem.product_info.forEach((item, index) => {
                            item.select = 1;
                            //默认选中
                            //item.id = order_ids[index]; //增加订单id
                                                        chooseNum++;
                            // if (item_ids) {
                            //   item_ids += ","+info[key][0][goodsKey].product_info[goodsItemKey].id
                            // } else {
                            //   item_ids = info[key][0][goodsKey].product_info[goodsItemKey].id
                            // }
                                                        if (item_ids) {
                                item_ids += "," + item.id;
                            } else {
                                item_ids = item.id;
                            }
                        });
                    });
                }
                that.setData({
                    chooseNum: chooseNum,
                    allSelect: data.bb || data.aa ? 1 : 0,
                    item_ids: item_ids,
                    all_item_ids: item_ids
                });
                //如果有返回值，状态码1，没有状态码0
                                var info = [];
                //全部状态下，接口有无订单
                                if (num == 0) {
                    if (res.extra.orders) {
                        if (res.extra.orders.length > 0) {
                            //状态码为1
                            that.setData({
                                info: data,
                                orderstatus: 1,
                                order_ids: res.extra.order_ids
                            });
                        } else {
                            //状态码为0
                            that.setData({
                                info: data,
                                orderstatus: 0,
                                order_ids: res.extra.order_ids,
                                pro_num: res.extra.pro_num,
                                order_num: res.extra.order_num
                            });
                        }
                    } else {
                        that.setData({
                            info: data,
                            orderstatus: 0,
                            order_ids: res.extra.order_ids,
                            pro_num: res.extra.pro_num,
                            order_num: res.extra.order_num
                        });
                    }
                    that.getAllOrder();
                } else {
                    //非全部状态,订单状态码维持原状
                    that.setData({
                        info: data
                    });
                }
            }
        });
    },
    //获取团长总单
    getAllOrder() {
        var that = this;
        var all_item_ids = that.data.all_item_ids;
        var date = that.data.date;
        common.request({
            endpoint: "My/waitpick/leader_general2",
            method: "post",
            data: {
                openid: wx.getStorageSync("user").openid,
                item_ids: all_item_ids
            },
            header: {
                "content-type": "application/json"
            },
            success: res => {
                var markers = [ {
                    iconPath: that.data.domain + "/img/mainPack/start_point.png",
                    id: 0,
                    latitude: res.extra.leader_latitude,
                    longitude: res.extra.leader_longitude,
                    width: 24,
                    height: 24
                } ];
                //仓库坐标有值
                                if (res.extra.store_latitude) {
                    qqmapsdk.direction({
                        from: res.extra.store_latitude + "," + res.extra.store_longitude,
                        to: res.extra.leader_latitude + "," + res.extra.leader_longitude,
                        success(qqres) {
                            console.log(qqres, "ddd");
                            var coors = qqres.result.routes[0].polyline;
                            var points = [];
                            for (var i = 2; i < coors.length; i++) {
                                coors[i] = coors[i - 2] + coors[i] / 1e6;
                            }
                            for (var i = 0; i < coors.length; i += 2) {
                                points.push({
                                    latitude: coors[i],
                                    longitude: coors[i + 1]
                                });
                            }
                            var polyline = [ {
                                points: points,
                                color: "#969696",
                                width: 3,
                                dottedLine: false
                            } ];
                            markers.push({
                                iconPath: that.data.domain + "/img/mainPack/end_point.png",
                                id: 1,
                                latitude: res.extra.store_latitude,
                                longitude: res.extra.store_longitude,
                                width: 24,
                                height: 24
                            });
                            that.setData({
                                AllOrder: res.extra,
                                polyline: polyline,
                                markers: markers
                            });
                        },
                        fail(err) {}
                    });
                } else {
                    that.setData({
                        AllOrder: res.extra,
                        markers: markers,
                        polyline: []
                    });
                }
            }
        });
    },
    getValue: function(e) {
        var that = this;
        var search_con = e.detail.value;
        that.setData({
            search_con: search_con
        });
    },
    search: function(e) {
        var that = this;
        var clerk = that.data.clerk;
        var openid = "";
        if (clerk.wom_status == 0) {
            openid = wx.getStorageSync("user").openid;
        } else {
            openid = clerk.leader_openid;
        }
        var search_con = that.data.search_con;
        var date = that.data.date;
        common.request({
            endpoint: "My/waitpick/wait_confirm",
            method: "post",
            data: {
                openid: openid,
                key_word: search_con,
                date: date
            },
            header: {
                "content-type": "application/json"
            },
            success: res => {
                that.setData({
                    info: res.extra
                });
            }
        });
    },
    scancode: function() {
        var that = this;
        var clerk = that.data.clerk;
        var openid = "";
        if (clerk.wom_status == 0) {
            openid = wx.getStorageSync("user").openid;
        } else {
            openid = clerk.leader_openid;
        }
        wx.scanCode({
            success: res => {
                console.log(res);
                var result = res.result;
                wx.showModal({
                    title: "提示",
                    content: "是否确认该团员已取货！",
                    success: function(res) {
                        if (res.cancel) {} else {
                            common.request({
                                endpoint: "My/qrcode/change_status_bycode",
                                method: "post",
                                data: {
                                    openid: openid,
                                    result: result
                                },
                                header: {
                                    "content-type": "application/json"
                                },
                                success: res => {
                                    wx.showToast({
                                        title: "取货成功",
                                        icon: "success"
                                    });
                                },
                                fail: res => {
                                    if (res.code == 4) {
                                        wx.showToast({
                                            title: res.message,
                                            icon: "none"
                                        });
                                    } else {
                                        wx.showToast({
                                            title: "取货失败",
                                            icon: "none"
                                        });
                                    }
                                }
                            });
                        }
                    },
                    fail: function(res) {}
                });
            }
        });
    },
    /**
   * 选择订单
   */
    chooseOrder(e) {
        let that = this;
        var idx = e.currentTarget.dataset.itemidx.split(",");
        var info = that.data.info;
        var deliveryWay = e.currentTarget.dataset.deliveryway;
        var num = 0;
        var chooseNum = 0;
        var item_ids = "";
        if (deliveryWay == 0 && info.aa) {
            if (info.aa[0][idx[0]].product_info[idx[1]].select == 1) {
                info.aa[0][idx[0]].product_info[idx[1]].select = 0;
                for (var key in info) {
                    if (info[key]) {
                        for (var goodsKey in info[key][0]) {
                            //有未选中的订单，数量加1
                            for (var goodsItemKey in info[key][0][goodsKey].product_info) {
                                if (info[key][0][goodsKey].product_info[goodsItemKey].select == 0) {
                                    num++;
                                } else {
                                    chooseNum++;
                                    if (item_ids) {
                                        item_ids += "," + info[key][0][goodsKey].product_info[goodsItemKey].id;
                                    } else {
                                        item_ids = info[key][0][goodsKey].product_info[goodsItemKey].id;
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                info.aa[0][idx[0]].product_info[idx[1]].select = 1;
                for (var key in info) {
                    console.log(info[key][0]);
                    if (info[key]) {
                        for (var goodsKey in info[key][0]) {
                            //有未选中的订单，数量加1
                            for (var goodsItemKey in info[key][0][goodsKey].product_info) {
                                if (info[key][0][goodsKey].product_info[goodsItemKey].select == 0) {
                                    num++;
                                } else {
                                    chooseNum++;
                                    if (item_ids) {
                                        item_ids += "," + info[key][0][goodsKey].product_info[goodsItemKey].id;
                                    } else {
                                        item_ids = info[key][0][goodsKey].product_info[goodsItemKey].id;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } else if (deliveryWay == 1 && info.bb) {
            if (info.bb[0][idx[0]].product_info[idx[1]].select == 1) {
                info.bb[0][idx[0]].product_info[idx[1]].select = 0;
                for (var key in info) {
                    if (info[key]) {
                        for (var goodsKey in info[key][0]) {
                            //有未选中的订单，数量加1
                            for (var goodsItemKey in info[key][0][goodsKey].product_info) {
                                if (info[key][0][goodsKey].product_info[goodsItemKey].select == 0) {
                                    num++;
                                } else {
                                    chooseNum++;
                                    if (item_ids) {
                                        item_ids += "," + info[key][0][goodsKey].product_info[goodsItemKey].id;
                                    } else {
                                        item_ids = info[key][0][goodsKey].product_info[goodsItemKey].id;
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                info.bb[0][idx[0]].product_info[idx[1]].select = 1;
                for (var key in info) {
                    console.log(info[key][0]);
                    if (info[key]) {
                        for (var goodsKey in info[key][0]) {
                            //有未选中的订单，数量加1
                            for (var goodsItemKey in info[key][0][goodsKey].product_info) {
                                if (info[key][0][goodsKey].product_info[goodsItemKey].select == 0) {
                                    num++;
                                } else {
                                    chooseNum++;
                                    if (item_ids) {
                                        item_ids += "," + info[key][0][goodsKey].product_info[goodsItemKey].id;
                                    } else {
                                        item_ids = info[key][0][goodsKey].product_info[goodsItemKey].id;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        that.setData({
            info: info,
            allSelect: num == 0 ? 1 : 0,
            chooseNum: chooseNum,
            item_ids: item_ids
        });
    },
    /**
   * 选择所有订单
   */
    chooseOrderAll() {
        let that = this;
        var info = that.data.info;
        var allSelect = that.data.allSelect;
        var chooseNum = 0;
        var item_ids = "";
        if (allSelect == 1 && (info.aa || info.bb)) {
            allSelect = 0;
            for (var key in info) {
                console.log(info[key][0]);
                if (info[key]) {
                    for (var goodsKey in info[key][0]) {
                        //有未选中的订单，数量加1
                        for (var goodsItemKey in info[key][0][goodsKey].product_info) {
                            info[key][0][goodsKey].product_info[goodsItemKey].select = 0;
                        }
                    }
                }
            }
        } else if (allSelect == 0 && (info.aa || info.bb)) {
            allSelect = 1;
            for (var key in info) {
                console.log(info[key][0]);
                if (info[key]) {
                    for (var goodsKey in info[key][0]) {
                        //有未选中的订单，数量加1
                        for (var goodsItemKey in info[key][0][goodsKey].product_info) {
                            info[key][0][goodsKey].product_info[goodsItemKey].select = 1;
                            chooseNum++;
                            if (item_ids) {
                                item_ids += "," + info[key][0][goodsKey].product_info[goodsItemKey].id;
                            } else {
                                item_ids = info[key][0][goodsKey].product_info[goodsItemKey].id;
                            }
                        }
                    }
                }
            }
        } else {
            allSelect = 0;
        }
        that.setData({
            allSelect: allSelect,
            info: info,
            chooseNum: chooseNum,
            item_ids: item_ids
        });
    },
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                that.setData({
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长"
                });
            }
        });
    }
});